<template>
  <div class="userManagement">
    <!-- 筛选搜索区域 -->
    <user-search
      :search="search"
      :labval="labval"
      :add="add"
      @onSearch="toSearch"
      @resetForm="resetForm"
      @addUser="addUser"
      @upload="upload"
    />
    <!-- 表格 -->
    <div class="userTable">
      <data-table
        :tableheader="tableheader"
        :datatable="tableDate"
        :loading="loading"
        :operation="operation"
        :client-height="clientHeight"
        @editData="editData($event)"
        @deleteData="deleteData($event)"
      />
    </div>
    <!-- 分页 -->
    <pagination
      :page="page"
      :count="count"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    ></pagination>
    <!-- 添加编辑弹窗 -->
    <add-dialog
      :title="dialogTitle"
      :dialogvisible="addEditDialog"
      @closeDialog="handleClose(form)"
      @determine="determine(dialogType)"
    >
      <template v-slot:add-content>
        <el-form
          ref="form"
          :model="form"
          label-width="90px"
          :rules="rules"
        >
          <el-form-item label="用户姓名:" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名称" />
          </el-form-item>
          <el-form-item label="联系电话:" prop="phone">
            <el-input
              v-model.number="form.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-form>
      </template>
    </add-dialog>
    <!-- 上传弹窗 -->
    <add-dialog
      :title="dialogTitle"
      :dialogvisible="uploadDialog"
      @closeDialog="closeUploadDialog"
      @determine="uploadFile(form)"
    >
      <template v-slot:add-content>
        <el-upload
           ref="upload"
          class="upload-demo"
          action="http://3x6686992i.zicp.vip/user/import"
          multiple
          accept=".xls,.xlsx"
          :auto-upload="false"
          :on-success="uploadSuccess"
        >
          <span tabindex="0">选择文件：</span>
          <el-button size="small" type="primary">点击选取文件</el-button>
        </el-upload>
        <el-link type="warning" href="http://3x6686992i.zicp.vip/user/templateDownload">下载模板</el-link>
      </template>
    </add-dialog>
    <!-- 删除弹窗 -->
    <add-dialog
      :title="dialogTitle"
      :dialogvisible="deleteDialog"
      @closeDialog="closeDelete"
      @determine="deleteUser(form)"
    >
      <template v-slot:add-content>
        <p class="deleteUser">是否确定删除该用户？</p>
      </template>
    </add-dialog>
  </div>
</template>

<script>
import UserSearch from "@/views/components/search";
import dataTable from "@/views/components/dataTable";
import addDialog from "@/views/components/addDialog";
import pagination from "@/views/components/pagination";
export default {
  components: {
    UserSearch,
    dataTable,
    addDialog,
    pagination,
  },
  data() {
    // 自定义表单验证规则
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("联系电话不能为空"));
      }
      setTimeout(() => {
        if (value.toString().length != 11) {
          callback(new Error("联系电话为11位数字"));
        } else {
          if (!/^1(3|4|5|6|7|8)\d{9}$/.test(value)) {
            callback(new Error("输入的电话号码不正确"));
          }else{
            callback();
          }
        }
      }, 100);
    };
    return {
      addEditDialog: false, //添加编辑弹窗开关
      uploadDialog: false, //上传弹窗开关
      deleteDialog: false, //删除弹窗开关
      loading: false, // 加载开关
      dialogTitle: "", //dialog弹窗名称
      dialogType: "0", //添加编辑弹窗类型 1为添加， 2为编辑
      deteleId: "",
      count: 0, //总数据量
      form: {}, //添加编辑框表单对象
      // 分页
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      // 搜索对象
      search: {
        type: "",
        keyword: "",
      },
      // 下拉框的值
      labval: [
        {
          label: "序号",
          value: "1",
        },
        {
          label: "用户姓名",
          value: "2",
        },
        {
          label: "联系电话",
          value: "3",
        },
      ],
      // 添加按钮
      add: [
        {
          name: "添加用户",
          click: "addUser",
        },
        {
          name: "导入用户",
          click: "upload",
        },
      ],
      clientHeight: "60vh",
      // 表头
      tableheader: [
        {
          label: "序号",
          prop: "id",
          width: "312",
          issort: true, //用于判断是否排序
        },
        {
          label: "用户姓名",
          prop: "username",
          width: "312",
          issort: false,
        },
        {
          label: "电话",
          prop: "phone",
          width: "312",
          issort: false,
        },
        {
          label: "添加时间",
          prop: "createTime",
          width: "322",
          issort: true,
        },
      ],
      // 数据列表
      tableDate: [],
      // 数据表操作项
      operation: {
        isedit: true,
        isdelete: true,
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 1, max: 4, message: "请输入用户名称", trigger: "blur" },
        ],
        phone: [{ required: true, validator: checkPhone, trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getTableData(this.page.pageNum, this.page.pageSize);
  },
  methods: {
    // 获取表格数据
    async getTableData(pageNum, pageSize) {
      this.loading = true;
      let res = await this.$http.get("/user/list", {
        params: {
          pageNum,
          pageSize,
        },
      });
      if (res.code == 0) {
        this.tableDate = res.data.list;
        this.count = res.data.count;
        this.loading = false;
      }
    },
    // 关闭添加编辑弹窗
    handleClose(form) {
      this.addEditDialog = false;
      this.form.username = '';
      this.form.phone = '';
    },
    // 关闭删除弹窗
    closeDelete() {
      this.deleteDialog = false;
    },
    // 上传弹窗关闭按钮
    closeUploadDialog() {
      this.uploadDialog = false;
      this.$refs.upload.clearFiles();
    },
    // 搜索
    async toSearch() {
      this.loading = true;
      let res = await this.$http.get("/user/list", {
        params: {
          type: this.search.type,
          keyword: this.search.keyword,
        },
      });
      if (res.code == 0) {
        this.tableDate = res.data.list;
        this.count = res.data.count;
        this.loading = false;
      }
    },
    // 重置按钮
    resetForm() {
      this.search.type = "";
      this.search.keyword = "";
      this.handleCurrentChange(1);
    },
    // 添加用户按钮事件
    addUser() {
      this.addEditDialog = true;
      this.dialogTitle = "添加用户";
      this.dialogType = "1";
    },
    // 上传点击事件
    upload() {
      this.dialogTitle = "导入用户";
      this.uploadDialog = true;
    },
    // 确认上传点击事件
    uploadFile() {
      this.$refs.upload.submit();
    },
    // 上传成功触发事件
    uploadSuccess(res) {
      this.$message({
        message: res.message,
        type: "success",
      });
      this.uploadDialog = false;
      this.$refs.upload.clearFiles();
      this.getTableData(this.page.pageNum, this.page.pageSize);
    },
    // 编辑按钮点击事件
    editData(row) {
      this.addEditDialog = true;
      this.dialogTitle = "编辑用户";
      this.dialogType = "2";
      this.form = JSON.parse(JSON.stringify(row)); //这里要注意深浅拷贝的问题
    },
    // 添加编辑弹窗确定按钮点击事件
    async determine(type) {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (type == 1) {
            let res = await this.$http.post("/user/saveOrUpdate", {
              username: this.form.username,
              phone: this.form.phone,
            });
            if (res.code == 0) {
              this.$message({
                message: res.message,
                type: "success",
              });
              this.addEditDialog = false;
              this.form.username = '';
              this.form.phone = '';
              this.handleCurrentChange(1)
            } else {
              this.$message.error("添加失败");
            }
          } else if (type == 2) {
            let res = await this.$http.post("/user/saveOrUpdate", {
              id: this.form.id,
              username: this.form.username,
              phone: this.form.phone,
            });
            if (res.code == 0) {
              this.$message({
                message: res.message,
                type: "success",
              });
              this.addEditDialog = false;
              this.form.id = '';
              this.form.username = '';
              this.form.phone = '';
              this.getTableData(this.page.pageNum, this.page.pageSize);
            } else {
              this.$message.error("编辑失败");
            }
          }
        } else {
          return false;
        }
      });
    },
    // 删除按钮点击事件
    deleteData(row) {
      this.dialogTitle = "删除用户";
      this.deleteDialog = true;
      this.deteleId = row.id;
    },
    // 确认删除点击事件
    async deleteUser() {
      let res = await this.$http.post("/user/delete", {
        id: this.deteleId,
      });
      if (res.code == 0) {
        this.$message({
          message: res.message,
          type: "success",
        });
        this.deleteDialog = false;
        this.getTableData();
      } else {
        this.$message.error("删除失败");
      }
    },
    // 页面数量改变时触发事件
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getTableData(this.page.pageNum, val);
    },
    // 当前页改变时触发事件
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getTableData(val, this.page.pageSize);
    },
  },
};
</script>

<style lang='scss'>
.userManagement {
  // margin: 20px;
  padding: 15px;
  .add-dialog {
      .el-link {
        a{
          color: #EA8B2D;
        }
      }

  }
  .deleteUser {
    text-align: center;
  }
}
</style>